<?php

class Admin_ProductsController extends Zend_Controller_Action
{
    protected function prepareData($data)
    {
        $validData = array();
        foreach($data as $index => $value) {
            $validData[$index] = strip_tags($value);
        }

        return $validData;
    }

    public function init()
    {
        require_once(APPLICATION_PATH . '/modules/admin/models/DbMapper/Products.php');
        require_once(APPLICATION_PATH . '/modules/admin/models/DbMapper/Categories.php');
        require_once(APPLICATION_PATH . '/modules/admin/models/DbTable/Products.php');
        require_once(APPLICATION_PATH . '/modules/admin/models/DbTable/Categories.php');
    }

    public function listAction()
    {
        $id = $this->getParam('id', null);
        if($id) {
            $productsDbMapper = new Admin_Model_DbMapper_Products();
            $categoriesDbMapper = new Admin_Model_DbMapper_Categories();

            $this->view->category = $categoriesDbMapper->selectById($id);
            $this->view->products = $productsDbMapper->selectByExpr(array('category_id = ?', $id));
        }
    }

    public function addAction()
    {
        if($this->_request->isPost()){
            $data = $this->_request->getPost();
            $data = $this->prepareData($data);

            $productsDbMapper = new Admin_Model_DbMapper_Products();
            $this->view->isInsert = $productsDbMapper->insert($data);
        }

        $categoryDbMapper = new Admin_Model_DbMapper_Categories();
        $this->view->categories = $categoryDbMapper->fetchAll();
        $this->view->categoryId = $this->getParam('id', null);
    }

    public function editAction() {
        $id = $this->getParam('id', null);
        $productDbMapper = new Admin_Model_DbMapper_Products();

        if($this->_request->isPost()) {
            $data = $this->_request->getPost();
            $data = $this->prepareData($data);
            $id = $productDbMapper->updateById($data, $id);

            if($id) {
                $this->view->isUpdate = $id;
            } else {
                $this->view->errorMessage = 'В процессе сохранения возникла ошибка';
            }
        }
        if($id) {
            $this->view->product = $productDbMapper->selectById($id);

            $categoryDbMapper = new Admin_Model_DbMapper_Categories();
            $this->view->categories = $categoryDbMapper->fetchAll();
        }
    }

    public function deleteAction() {}
}
?>
